﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using Assist;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Electrical;
using Autodesk.Revit.UI;
using YArchitech.Revit;
using YRevitJig;
using YJKRGeometry;

namespace ElectricDim
{
	public class ElectricalUtils
	{
		public static string GetMaxStr(List<string> lstItem)
		{
			string result = null;
			int num = 0;
			foreach (string text in lstItem)
			{
				byte[] bytes = Encoding.Default.GetBytes(text);
				if (num < bytes.Length)
				{
					num = bytes.Length;
					result = text;
				}
			}
			return result;
		}

		private static double GetAngle(XYZ ptOut)
		{
			XYZ xyz = ptOut - XYZ.Zero;
			return ElectricalUtils.formatAngle(XYZ.BasisX.AngleOnPlaneTo(xyz, XYZ.BasisZ));
		}

		private static double formatAngle(double angle)
		{
			int num = (int)(angle / Math.PI*2);
			double num2 = angle - (double)num * Math.PI*2;
			if (num2 < 0.0)
			{
				num2 += Math.PI*2;
			}
			return num2;
		}

		public static double PromtAngle(XYZ pickPt, Wire wire)
		{
			return AssistFunc.RadianToAngle(ElectricalUtils.GetAngle(ElectricalUtils.PromtLine(pickPt, wire).ComputeDerivatives(1.0, true).get_Basis(0)));
		}

		public static Line PromtLine(XYZ pickPt, Wire wire)
		{
			List<XYZ> list = RevitVersionFuncs.GetChamferWireCtrlPoints(wire.Document, wire);
			list = ElectricalUtils.EliminateCoincidencePoint(list);
			Line result = null;
			double num = 1000000.0;
			for (int i = 1; i < list.Count; i++)
			{
				Line line = Line.CreateBound(list[i], list[i - 1]);
				IntersectionResult intersectionResult = line.Project(pickPt);
				if (intersectionResult != null)
				{
					XYZ xyzpoint = intersectionResult.XYZPoint;
					double num2 = pickPt.DistanceTo(xyzpoint);
					if (num2 < num)
					{
						num = num2;
						result = line;
					}
				}
			}
			return result;
		}

		public static List<XYZ> EliminateCoincidencePoint(List<XYZ> pts)
		{
			List<XYZ> list = new List<XYZ>();
			using (List<XYZ>.Enumerator enumerator = pts.GetEnumerator())
			{
				while (enumerator.MoveNext())
				{
					XYZ pt = enumerator.Current;
					if (!list.Exists((XYZ item) => pt.IsAlmostEqualTo(item, 0.01)))
					{
						list.Add(pt);
					}
				}
			}
			return list;
		}

		public static Group CreateCableTrayDim(UIDocument uiDoc, XYZ ptS, XYZ ptDim, DlgCableTrayDim.CUserConfig dataDim)
		{
			Document document = uiDoc.Document;
            Autodesk.Revit.DB.View activeView = document.ActiveView;
            Autodesk.Revit.ApplicationServices.Application application = document.Application;
			List<string> lstItem = dataDim.m_lstItem;
			XYZ xyz = new XYZ(ptDim.X, ptDim.Y, ptS.Z);
			Plane plane = RevitVersionFuncs.CreatePlanByNormalAndOrigin(XYZ.BasisZ, ptS);
			SketchPlane.Create(document, plane);
			ElementSet elementSet = new ElementSet();
			if (dataDim.m_DimStyle != LeaderStyle.None)
			{
				new XYZ(ptDim.X, ptDim.Y, ptS.Z);
				if (dataDim.m_DimStyle == LeaderStyle.Orthogonal)
				{
					xyz = JigFuncs.GetOrthoPoint(uiDoc, xyz, ptS);
				}
				DetailLine detailLine = YJKRevitTools.DrawDetailLine(document, ptS, xyz);
				elementSet.Insert(detailLine);
				PointStyle linkLineStyle = dataDim.m_LinkLineStyle;
				if (linkLineStyle != PointStyle.Arrow)
				{
					if (linkLineStyle == PointStyle.Circle)
					{
						double radius = AssistFunc.mmToFeet(100.0);
						Arc arc = document.CreatYJKArc(ptS, radius, 0.0, Math.PI, XYZ.BasisX, XYZ.BasisY);
						Arc arc2 = document.CreatYJKArc(ptS, radius, Math.PI, Math.PI*2, XYZ.BasisX, XYZ.BasisY);
						DetailCurve detailCurve = YJKRevitTools.DrawRangLine(document, ptS, radius);
						elementSet.Insert(detailCurve);
						ElementId hatch = ElectricalUtils.GetHatch(document);
						List<CurveLoop> list = new List<CurveLoop>();
						CurveLoop curveLoop = new CurveLoop();
						curveLoop.Append(arc);
						curveLoop.Append(arc2);
						list.Add(curveLoop);
						FilledRegion filledRegion = FilledRegion.Create(document, hatch, activeView.Id, list);
						elementSet.Insert(filledRegion);
					}
				}
				else
				{
					XYZ xyz2 = (xyz - ptS).Normalize();
					Transform transform = Transform.CreateRotationAtPoint(XYZ.BasisZ, AssistFunc.AngleToRadian(15.0), XYZ.Zero);
					xyz2 = ElectricalUtils.TransformPoint(xyz2, transform);
					XYZ xyz3 = ptS + xyz2;
					DetailLine detailLine2 = YJKRevitTools.DrawDetailLine(document, ptS, xyz3);
					elementSet.Insert(detailLine2);
					Transform transform2 = Transform.CreateRotationAtPoint(XYZ.BasisZ, AssistFunc.AngleToRadian(-30.0), XYZ.Zero);
					xyz2 = ElectricalUtils.TransformPoint(xyz2, transform2);
					XYZ xyz4 = ptS + xyz2;
					DetailLine detailLine3 = YJKRevitTools.DrawDetailLine(document, ptS, xyz4);
					elementSet.Insert(detailLine3);
					Line line = Line.CreateBound(ptS, xyz3);
					Line line2 = Line.CreateBound(xyz3, xyz4);
					Line line3 = Line.CreateBound(xyz4, ptS);
					List<CurveLoop> list2 = new List<CurveLoop>();
					ElementId hatch2 = ElectricalUtils.GetHatch(document);
					CurveLoop curveLoop2 = new CurveLoop();
					curveLoop2.Append(line);
					curveLoop2.Append(line2);
					curveLoop2.Append(line3);
					list2.Add(curveLoop2);
					FilledRegion filledRegion2 = FilledRegion.Create(document, hatch2, activeView.Id, list2);
					elementSet.Insert(filledRegion2);
				}
			}
			IEnumerable<Element> enumerable = new FilteredElementCollector(document).OfClass(typeof(TextNoteType)).ToElements();
			double num = AssistFunc.mmToFeet(3.0);
			double num2 = 0.7;
			ElementId elementId = new ElementId(0);
			foreach (Element element in enumerable)
			{
				TextNoteType textNoteType = (TextNoteType)element;
				if (textNoteType.Name == "HY-微软雅黑-3.0-0.7")
				{
					num = textNoteType.get_Parameter(BuiltInParameter.TEXT_SIZE).AsDouble();
					num2 = textNoteType.get_Parameter(BuiltInParameter.TEXT_WIDTH_SCALE).AsDouble();
					elementId = textNoteType.Id;
					break;
				}
			}
			string maxStr = ElectricalUtils.GetMaxStr(lstItem);
			byte[] bytes = Encoding.Default.GetBytes(maxStr);
			double num3 = num * num2;
			double num4 = (double)bytes.Length * num3;
			num *= 2.0;
			XYZ xyz5 = null;
			XYZ xyz6 = null;
			XYZ xyz7 = xyz;
            TextAlignFlags textAlign = (TextAlignFlags)2112;
			if (ptDim.X < ptS.X)
			{
				if (ptDim.Y < ptS.Y)
				{
					xyz5 = -XYZ.BasisY * num * (double)activeView.Scale;
					xyz6 = -XYZ.BasisX * num4 * (double)activeView.Scale;
                    textAlign = (TextAlignFlags)2304;
				}
				else
				{
					xyz5 = XYZ.BasisY * num * (double)activeView.Scale;
					xyz6 = -XYZ.BasisX * num4 * (double)activeView.Scale;
					lstItem.Reverse();
                    textAlign = (TextAlignFlags)2304;
				}
			}
			else if (ptDim.Y < ptS.Y)
			{
				xyz5 = -XYZ.BasisY * num * (double)activeView.Scale;
				xyz6 = XYZ.BasisX * num4 * (double)activeView.Scale;
				xyz7 += XYZ.BasisX * AssistFunc.mmToFeet(60.0);
			}
			else
			{
				xyz5 = XYZ.BasisY * num * (double)activeView.Scale;
				xyz6 = XYZ.BasisX * num4 * (double)activeView.Scale;
				lstItem.Reverse();
			}
			int quar = ElectricalUtils.Quadrant(ptS, ptDim);
			xyz7 = RevitElementExtension.GetTextNotePosition(xyz7, quar, num, num4, activeView);
			foreach (string strText in lstItem)
			{
				TextNote textNode = document.GetTextNode(activeView, xyz7, XYZ.BasisX, XYZ.BasisY, num4 * 2.0, textAlign, strText);
				textNode.ChangeTypeId(elementId);
				elementSet.Insert(textNode);
				DetailLine detailLine4 = YJKRevitTools.DrawDetailLine(document, xyz, xyz + xyz6);
				elementSet.Insert(detailLine4);
				DetailLine detailLine5 = YJKRevitTools.DrawDetailLine(document, xyz, xyz + xyz5);
				elementSet.Insert(detailLine5);
				foreach (ElementId elementId2 in ElementTransformUtils.CopyElement(document, detailLine5.Id, xyz6))
				{
					elementSet.Insert(document.GetElement(elementId2));
				}
				xyz += xyz5;
				xyz7 += xyz5;
			}
			DetailLine detailLine6 = YJKRevitTools.DrawDetailLine(document, xyz, xyz + xyz6);
			elementSet.Insert(detailLine6);
			return document.CreatYJKGroup(elementSet);
		}

		public static XYZ GetOrthogonalXYZ(XYZ ptDimFirst, XYZ ptDimSecond)
		{
			double num = ptDimFirst.DistanceTo(ptDimSecond);
			XYZ xyz = ptDimSecond - ptDimFirst;
			double num2 = XYZ.BasisX.AngleOnPlaneTo(xyz, XYZ.BasisZ);
			int num3 = ElectricalUtils.Quadrant8(num2, true);
			if (num3 == 1 || num3 == 8)
			{
				xyz = XYZ.BasisX;
			}
			else if (num3 == 2 || num3 == 3)
			{
				xyz = XYZ.BasisY;
			}
			else if (num3 == 4 || num3 == 5)
			{
				xyz = -XYZ.BasisX;
			}
			else if (num3 == 6 || num3 == 7)
			{
				xyz = -XYZ.BasisY;
			}
			ptDimSecond = ptDimFirst + xyz * (num * Math.Abs(Math.Sin(num2)));
			return ptDimSecond;
		}

		public static int Quadrant(XYZ ptBase, XYZ ptTag)
		{
			XYZ xyz = ptTag - ptBase;
			return ElectricalUtils.Quadrant(XYZ.BasisX.AngleOnPlaneTo(xyz, XYZ.BasisZ), true);
		}

		public static int Quadrant(double angle, bool arc)
		{
			if (!arc)
			{
				if (angle > 0.0 && angle <= 90.0)
				{
					return 1;
				}
				if (angle > 90.0 && angle <= 180.0)
				{
					return 2;
				}
				if (angle > 180.0 && angle < 270.0)
				{
					return 3;
				}
				return 4;
			}
			else
			{
				if (Geometry.GreaterThan(angle, 0.0) && Geometry.Lessthan_Or_Equal(angle, Math.PI*.5))
				{
					return 1;
				}
				if (Geometry.GreaterThan(angle, Math.PI*.5) && Geometry.Lessthan_Or_Equal(angle, Math.PI))
				{
					return 2;
				}
				if (Geometry.GreaterThan(angle, Math.PI) && Geometry.Lessthan_Or_Equal(angle, 4.71238898038469))
				{
					return 3;
				}
				return 4;
			}
		}

		public static int Quadrant8(double angle, bool arc)
		{
			if (!arc)
			{
				if (angle > 0.0 && angle <= 45.0)
				{
					return 1;
				}
				if (angle > 45.0 && angle <= 90.0)
				{
					return 2;
				}
				if (angle > 90.0 && angle <= 135.0)
				{
					return 3;
				}
				if (angle > 135.0 && angle <= 180.0)
				{
					return 4;
				}
				if (angle > 180.0 && angle <= 225.0)
				{
					return 5;
				}
				if (angle > 225.0 && angle <= 270.0)
				{
					return 6;
				}
				if (angle > 270.0 && angle <= 315.0)
				{
					return 7;
				}
				return 8;
			}
			else
			{
				if (Geometry.GreaterThan(angle, 0.0) && angle < 0.78539816339744828)
				{
					return 1;
				}
				if (Geometry.GreaterThan(angle, 0.78539816339744828) && Geometry.Lessthan_Or_Equal(angle, Math.PI*.5))
				{
					return 2;
				}
				if (Geometry.GreaterThan(angle, Math.PI*.5) && Geometry.Lessthan_Or_Equal(angle, 1.1780972450961724))
				{
					return 3;
				}
				if (Geometry.GreaterThan(angle, 2.3561944901923448) && Geometry.Lessthan_Or_Equal(angle, Math.PI))
				{
					return 4;
				}
				if (Geometry.GreaterThan(angle, Math.PI) && Geometry.Lessthan_Or_Equal(angle, 3.9269908169872414))
				{
					return 5;
				}
				if (Geometry.GreaterThan(angle, 3.9269908169872414) && Geometry.Lessthan_Or_Equal(angle, 4.71238898038469))
				{
					return 6;
				}
				if (Geometry.GreaterThan(angle, 4.71238898038469) && Geometry.Lessthan_Or_Equal(angle, 5.497787143782138))
				{
					return 7;
				}
				return 8;
			}
		}

		private static int GetMaxStrCount(List<string> lstItem)
		{
			int num = 0;
			foreach (string s in lstItem)
			{
				byte[] bytes = Encoding.Default.GetBytes(s);
				if (num < bytes.Length)
				{
					num = bytes.Length;
				}
			}
			return num;
		}

		public static ElementId GetHatch(Document doc)
		{
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc);
			filteredElementCollector.OfClass(typeof(FilledRegionType));
			FilledRegionType filledRegionType = null;
			foreach (Element element in filteredElementCollector.ToElements())
			{
				if (element.Name == "black")
				{
					filledRegionType = (element as FilledRegionType);
					break;
				}
			}
			if (filledRegionType == null)
			{
				SubTransaction subTransaction = new SubTransaction(doc);
				subTransaction.Start();
				ElementId fillPatternId = new ElementId(19);
				filledRegionType = ((filteredElementCollector.ToElements()[0] as FilledRegionType).Duplicate("black") as FilledRegionType);
				FilteredElementCollector filteredElementCollector2 = new FilteredElementCollector(doc);
				filteredElementCollector2.OfClass(typeof(FillPatternElement));
				foreach (Element element2 in filteredElementCollector2.ToElements())
				{
					if (element2.Name == "实体填充")
					{
						fillPatternId = element2.Id;
						break;
					}
				}
				filledRegionType.FillPatternId = fillPatternId;
				subTransaction.Commit();
			}
			return filledRegionType.Id;
		}

		public static XYZ TransformPoint(XYZ point, Transform transform)
		{
			double x = point.X;
			double y = point.Y;
			double z = point.Z;
			XYZ xyz = transform.get_Basis(0);
			XYZ xyz2 = transform.get_Basis(1);
			XYZ xyz3 = transform.get_Basis(2);
			XYZ origin = transform.Origin;
			double num = x * xyz.X + y * xyz2.X + z * xyz3.X + origin.X;
			double num2 = x * xyz.Y + y * xyz2.Y + z * xyz3.Y + origin.Y;
			double num3 = x * xyz.Z + y * xyz2.Z + z * xyz3.Z + origin.Z;
			return new XYZ(num, num2, num3);
		}

        public static Autodesk.Revit.DB.ElementType GetLeaderType(Document doc, PointStyle style, Family labelFamily)
		{
			if (labelFamily == null)
			{
				return null;
			}
            Autodesk.Revit.DB.ElementType elementType = null;
			if (style == PointStyle.Arrow)
			{
				string text = "箭头引线";
				foreach (FamilySymbol familySymbol in labelFamily.GetSymbols())
				{
					if (familySymbol.Name == text)
					{
						elementType = familySymbol;
						break;
					}
				}
				if (elementType != null)
				{
					return elementType;
				}
				SubTransaction subTransaction = new SubTransaction(doc);
				try
				{
					subTransaction.Start();
					elementType = labelFamily.GetSymbols()[0].Duplicate(text);
					ElementId labelArrowStyle = ElectricalUtils.GetLabelArrowStyle(doc);
					elementType.get_Parameter(BuiltInParameter.LEADER_ARROWHEAD).Set(labelArrowStyle);
					subTransaction.Commit();
					return elementType;
				}
				catch (Exception)
				{
					subTransaction.RollBack();
					return elementType;
				}
			}
			if (style == PointStyle.Circle)
			{
				string text2 = "实心点引线";
				foreach (FamilySymbol familySymbol2 in labelFamily.GetSymbols())
				{
					if (familySymbol2.Name == text2)
					{
						elementType = familySymbol2;
						break;
					}
				}
				if (elementType != null)
				{
					return elementType;
				}
				SubTransaction subTransaction2 = new SubTransaction(doc);
				try
				{
					subTransaction2.Start();
					elementType = labelFamily.GetSymbols()[0].Duplicate(text2);
					ElementId labelCircleStyle = ElectricalUtils.GetLabelCircleStyle(doc);
					elementType.get_Parameter(BuiltInParameter.LEADER_ARROWHEAD).Set(labelCircleStyle);
					subTransaction2.Commit();
					return elementType;
				}
				catch (Exception)
				{
					subTransaction2.RollBack();
					return elementType;
				}
			}
			if (style == PointStyle.Line)
			{
				string text3 = "短斜线";
				foreach (FamilySymbol familySymbol3 in labelFamily.GetSymbols())
				{
					if (familySymbol3.Name == text3)
					{
						elementType = familySymbol3;
						break;
					}
				}
				if (elementType != null)
				{
					return elementType;
				}
				SubTransaction subTransaction3 = new SubTransaction(doc);
				try
				{
					subTransaction3.Start();
					elementType = labelFamily.GetSymbols()[0].Duplicate(text3);
					ElementId labelLineStyle = ElectricalUtils.GetLabelLineStyle(doc);
					elementType.get_Parameter(BuiltInParameter.LEADER_ARROWHEAD).Set(labelLineStyle);
					subTransaction3.Commit();
					return elementType;
				}
				catch (Exception)
				{
					subTransaction3.RollBack();
					return elementType;
				}
			}
			string text4 = "空引线";
			foreach (FamilySymbol familySymbol4 in labelFamily.GetSymbols())
			{
				if (familySymbol4.Name == text4)
				{
					elementType = familySymbol4;
					break;
				}
			}
			if (elementType == null)
			{
				SubTransaction subTransaction4 = new SubTransaction(doc);
				try
				{
					subTransaction4.Start();
					elementType = labelFamily.GetSymbols()[0].Duplicate(text4);
					ElementId labelNullStyle = ElectricalUtils.GetLabelNullStyle(doc);
					elementType.get_Parameter(BuiltInParameter.LEADER_ARROWHEAD).Set(labelNullStyle);
					subTransaction4.Commit();
				}
				catch (Exception)
				{
					subTransaction4.RollBack();
				}
			}
			return elementType;
		}

		public static ElementId GetLabelArrowStyle(Document doc)
		{
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc);
            filteredElementCollector.OfClass(typeof(Autodesk.Revit.DB.ElementType));
			string value = "实心箭头";
			foreach (Element element in filteredElementCollector.ToElements())
			{
				if (element.Name.Contains(value))
				{
					return element.Id;
				}
			}
            return (filteredElementCollector.ToElements()[0] as Autodesk.Revit.DB.ElementType).Id;
		}

		public static ElementId GetLabelCircleStyle(Document doc)
		{
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc);
            filteredElementCollector.OfClass(typeof(Autodesk.Revit.DB.ElementType));
			string value = "实心点";
			foreach (Element element in filteredElementCollector.ToElements())
			{
				if (element.Name.Contains(value))
				{
					return element.Id;
				}
			}
            return (filteredElementCollector.ToElements()[0] as Autodesk.Revit.DB.ElementType).Id;
		}

		public static ElementId GetLabelLineStyle(Document doc)
		{
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc);
            filteredElementCollector.OfClass(typeof(Autodesk.Revit.DB.ElementType));
			string value = "对角线";
			foreach (Element element in filteredElementCollector.ToElements())
			{
				if (element.Name.Contains(value))
				{
					return element.Id;
				}
			}
            return (filteredElementCollector.ToElements()[0] as Autodesk.Revit.DB.ElementType).Id;
		}

		public static ElementId GetLabelNullStyle(Document doc)
		{
			return new ElementId(-1);
		}

		public static LinkCurve GetLinkWire(UIApplication uiApp, List<Reference> referenceList)
		{
			Document document = uiApp.ActiveUIDocument.Document;
			LinkCurve linkCurve = new LinkCurve();
            Autodesk.Revit.DB.View activeView = document.ActiveView;
			LinkCurve result;
			try
			{
				foreach (Curve curve in RevitVersionFuncs.GetWireCurve(document.GetElement(referenceList[0].ElementId) as Wire, activeView))
				{
					linkCurve.Add(curve);
				}
				foreach (Reference reference in referenceList)
				{
					Wire wire = document.GetElement(reference.ElementId) as Wire;
					Curve curve2 = (wire.Location as LocationCurve).Curve;
					foreach (Reference reference2 in referenceList)
					{
						if (reference != reference2)
						{
							Wire wire2 = document.GetElement(reference2.ElementId) as Wire;
							Curve curve3 = (wire2.Location as LocationCurve).Curve;
							if (curve3 != null)
							{
								IntersectionResultArray intersectionResultArray = new IntersectionResultArray();
                                curve2.Intersect(curve3, out intersectionResultArray);
								if (intersectionResultArray != null)
								{
									foreach (object obj in intersectionResultArray)
									{
										IntersectionResult intersectionResult = (IntersectionResult)obj;
										try
										{
											XYZ hyendPoint = curve2.GetEndPoint(0);
											XYZ hyendPoint2 = curve2.GetEndPoint(1);
											if ((intersectionResult.XYZPoint.IsAlmostEqualTo(hyendPoint) || intersectionResult.XYZPoint.IsAlmostEqualTo(hyendPoint2)) && linkCurve.IsContains(uiApp, RevitVersionFuncs.GetWireCurve(wire, activeView)[0]) && !linkCurve.IsContains(uiApp, RevitVersionFuncs.GetWireCurve(wire2, activeView)[0]))
											{
												foreach (Curve curve4 in RevitVersionFuncs.GetWireCurve(wire2, activeView))
												{
													linkCurve.Add(curve4);
												}
											}
											break;
										}
										catch
										{
											break;
										}
									}
								}
							}
						}
					}
				}
				if (linkCurve.Count < referenceList.Count)
				{
					throw new Exception("选择的集合中存在多条链接线或分支，请重新选择。");
				}
				result = linkCurve;
			}
			catch (Exception)
			{
				string text = "选择的集合中存在多条链接线或分支，请重新选择。";
				MessageBox.Show(text);
				throw new Exception(text);
			}
			return result;
		}

		public static LinkCurve GetLinkWall(UIApplication uiApp)
		{
			Document document = uiApp.ActiveUIDocument.Document;
			LinkCurve linkCurve = new LinkCurve();
            Autodesk.Revit.DB.View activeView = document.ActiveView;
			List<Reference> list = null;
			try
			{
				list = uiApp.ActiveUIDocument.Selection.PickObjects(Autodesk.Revit.UI.Selection.ObjectType.Element, "请选择墙作为沿线").ToList<Reference>();
			}
			catch
			{
				string text = "没有选择阵列沿线。";
				MessageBox.Show(text);
				throw new Exception(text);
			}
			LinkCurve result;
			try
			{
				Wall wall = document.GetElement(list[0].ElementId) as Wall;
				linkCurve.Add((wall.Location as LocationCurve).Curve);
				foreach (Reference reference in list)
				{
					Curve curve = ((document.GetElement(reference.ElementId) as Wall).Location as LocationCurve).Curve;
					foreach (Reference reference2 in list)
					{
						if (reference != reference2)
						{
							Curve curve2 = ((document.GetElement(reference2.ElementId) as Wall).Location as LocationCurve).Curve;
							if (curve2 != null)
							{
								IntersectionResultArray intersectionResultArray = new IntersectionResultArray();
                                curve.Intersect(curve2, out intersectionResultArray);
								if (intersectionResultArray != null)
								{
									foreach (object obj in intersectionResultArray)
									{
										IntersectionResult intersectionResult = (IntersectionResult)obj;
										try
										{
											XYZ hyendPoint = curve.GetEndPoint(0);
											XYZ hyendPoint2 = curve.GetEndPoint(1);
											if ((intersectionResult.XYZPoint.IsAlmostEqualTo(hyendPoint) || intersectionResult.XYZPoint.IsAlmostEqualTo(hyendPoint2)) && linkCurve.IsContains(uiApp, curve) && !linkCurve.IsContains(uiApp, curve2))
											{
												linkCurve.Add(curve2);
											}
											break;
										}
										catch
										{
											break;
										}
									}
								}
							}
						}
					}
				}
				if (linkCurve.Count < list.Count)
				{
					throw new Exception("选择的集合中存在多条链接线或分支，请重新选择。");
				}
				result = linkCurve;
			}
			catch (Exception)
			{
				string text2 = "选择的集合中存在多条链接线或分支，请重新选择。";
				MessageBox.Show(text2);
				throw new Exception(text2);
			}
			return result;
		}

		public static void ViewValidating(Document doc)
		{
            Autodesk.Revit.DB.View activeView = doc.ActiveView;
			if (activeView is ViewPlan)
			{
				ViewPlan viewPlan = activeView as ViewPlan;
				if (viewPlan.SketchPlane == null)
				{
					Plane plane = RevitVersionFuncs.CreatePlanByOriginAndBasis(viewPlan.Origin, viewPlan.RightDirection, viewPlan.UpDirection);
					Transaction transaction = new Transaction(doc);
					transaction.Start("new sketchPlane");
					SketchPlane sketchPlane = RevitVersionFuncs.NewSketchPlane(doc, plane);
					activeView.SketchPlane = sketchPlane;
					transaction.Commit();
					return;
				}
			}
			else if (activeView is ViewSection)
			{
				ViewSection viewSection = activeView as ViewSection;
				if (viewSection.SketchPlane == null)
				{
					Plane plane2 = RevitVersionFuncs.CreatePlanByOriginAndBasis(viewSection.Origin, viewSection.RightDirection, viewSection.UpDirection);
					Transaction transaction2 = new Transaction(doc);
					transaction2.Start("new sketchPlane");
					SketchPlane sketchPlane2 = RevitVersionFuncs.NewSketchPlane(doc, plane2);
					activeView.SketchPlane = sketchPlane2;
					transaction2.Commit();
				}
			}
		}

		public static bool ReadWriteLigAndGroundXMLFileItem(ref int lightningSize, ref int groundSize, bool bSave = true)
		{
			string text = Path.GetTempPath() + "lightning.xml";
			if (!new FileInfo(text).Exists)
			{
				ElectricalUtils.CreateXml(text);
			}
			try
			{
				XmlDocument xmlDocument = new XmlDocument();
				xmlDocument.Load(text);
				if (bSave)
				{
					XmlNode documentElement = xmlDocument.DocumentElement;
					XmlNode xmlNode = xmlDocument.CreateNode(XmlNodeType.Element, "Data", null);
					XmlAttribute xmlAttribute = xmlDocument.CreateAttribute("LinghtningSize");
					xmlAttribute.InnerText = lightningSize.ToString();
					xmlNode.Attributes.Append(xmlAttribute);
					xmlAttribute = xmlDocument.CreateAttribute("GroundSize");
					xmlAttribute.InnerText = groundSize.ToString();
					xmlNode.Attributes.Append(xmlAttribute);
					documentElement.AppendChild(xmlNode);
					xmlDocument.Save(text);
				}
				else
				{
					xmlDocument.Load(text);
					XmlElement documentElement2 = xmlDocument.DocumentElement;
					XmlNode namedItem = documentElement2.Attributes.GetNamedItem("LinghtningSize");
					lightningSize = Convert.ToInt32(namedItem.Value);
					XmlNode namedItem2 = documentElement2.Attributes.GetNamedItem("GroundSize");
					groundSize = Convert.ToInt32(namedItem2.Value);
				}
			}
			catch (Exception ex)
			{
				TaskDialog.Show("读、写XML文件出现问题:", ex.Message);
				return false;
			}
			return true;
		}

		private static void CreateXml(string fileName)
		{
			XmlDocument xmlDocument = new XmlDocument();
			XmlNode xmlNode = xmlDocument.CreateNode(XmlNodeType.Element, "Data", null);
			XmlDeclaration newChild = xmlDocument.CreateXmlDeclaration("1.0", "utf-8", null);
			xmlDocument.InsertBefore(newChild, xmlDocument.DocumentElement);
			XmlAttribute xmlAttribute = xmlDocument.CreateAttribute("LinghtningSize");
			xmlAttribute.InnerText = "1000";
			xmlNode.Attributes.Append(xmlAttribute);
			xmlAttribute = xmlDocument.CreateAttribute("GroundSize");
			xmlAttribute.InnerText = "5000";
			xmlNode.Attributes.Append(xmlAttribute);
			xmlDocument.AppendChild(xmlNode);
			xmlDocument.Save(fileName);
		}

		public static void DeleteTagOfElement(Document doc, Wire wire, string param)
		{
			foreach (Element element in new FilteredElementCollector(doc, doc.ActiveView.Id).OfClass(typeof(IndependentTag)).OfCategory(BuiltInCategory.OST_WireTags).ToElements())
			{
				IndependentTag independentTag = element as IndependentTag;
				if (independentTag.TaggedLocalElementId == wire.Id)
				{
					Parameter parameter = (doc.GetElementById(independentTag.GetTypeId()) as FamilySymbol).GetParameter("标记类别");
					if (parameter != null && parameter.AsString() == param)
					{
						doc.Delete(independentTag.Id);
						doc.Regenerate();
						break;
					}
				}
			}
		}
	}
}
